package com.test.daily.leetcode.y2022.m04.day0404.v1;

/**
 * @author Tom on 2022/4/4
 */
public class NumArray {
    private int[] sum;
    private int size;
    private int[] nums;
    public NumArray(int[] nums) {
        this.nums = nums;
        int n = nums.length;
        size = (int) Math.sqrt(n);
        sum = new int[(n + size -1)/size];
        for(int i = 0; i < n; i++){
            sum[i / size] += nums[i];
        }
    }
    public void update(int index, int val) {
        sum[index / size] += val - nums[index];
        nums[index] = val;
    }

    public int sumRange(int left, int right) {
        int b1 = left / size, i1 = left % size, b2 = right / size, i2 = right % size;
        if(b1 == b2){
            int sum = 0;
            for(int j = i1; j <= i2; j++){
                sum += nums[b1 * size + 1];
            }
            return sum;
        }
        int sum1 = 0;
        for(int j = i1; j < size; j++){
            sum1 += nums[b1* size + j];
        }
        int sum2 = 0;
        for(int j = 0; j <= i2; j++){
            sum2 += nums[b2*size +j];
        }
        int sum3 = 0;
        for(int j = b1 + 1; j< b2; j++){
            sum3 += sum[j];
        }
        return sum1 + sum2 + sum3;

    }
}


















